package cn.gz.demo.ui

import android.os.Bundle
import android.util.Log
import androidx.databinding.DataBindingUtil
import cn.gz.demo.KotlinBinding
import cn.gz.demo.R
import cn.gz.demo.ui.base.BaseActivity
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking

/**
 * @author Liuyz
 * @date 2020/6/1514:45
 */
class KotlinActivity : BaseActivity() {
    private var binding: KotlinBinding? = null
    private var TAG: String? = "Liuyz"
    var i = 10
    var s = "i=$i"
    var str = "$s.length is ${s.length}"
    val price = "${'$'}9.99"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_kotlin)

//        Log.e(TAG, "主线程id：${mainLooper.thread.id}")
//        test()
//        Log.e(TAG, "协程执行结束")

//        repeat(100) {
//            GlobalScope.launch {
//                delay(500L)
//                Log.e(TAG, "协程执行结束 -- 线程id：${Thread.currentThread().id}")
//            }
//        }
//        Log.e(TAG, "主线程执行结束")

//        runBlocking {
//            repeat(100_10) {
//                GlobalScope.launch {
//                    delay(500L)
//                    Log.e(TAG, "协程执行结束 -- 线程id：${Thread.currentThread().id}")
//                }
//            }
//        }
//
//        //使用async并发
//        runBlocking {
//            val time = measureTimeMillis {
//                val one = GlobalScope.async { doSomethingOne() }
//                val two = GlobalScope.async { doSomethingTwo() }
//                Log.e(TAG, "async the answer is ${one.await() + two.await()}")
//            }
//            Log.e(TAG, "async Completed in $time ms    " + Thread.currentThread().name)
//        }

//        GlobalScope.launch {
//            val token = getToken()
//            val userInfo = getUserInfo(token)
//            setUserInfo(userInfo)
//        }
//        repeat(8) {
//            Log.e(TAG, "主线程执行$it")
//        }

        Log.e(TAG, " ......i:"+i);
        Log.e(TAG, " ......s:"+s);
        Log.e(TAG, " ......str:"+str);
        Log.e(TAG, " ......price:"+price);
    }

    private fun setUserInfo(userInfo: String) {
        Log.e(TAG, userInfo)
    }

    private suspend fun getToken(): String {
        delay(2000)
        return "token"
    }

    private suspend fun getUserInfo(token: String): String {
        delay(2000)
        return "$token - userInfo"
    }

    //挂起函数
    suspend fun doSomethingOne(): Int {
        delay(1000L) //假设在这里做了一些有用的事
        return 22
    }

    suspend fun doSomethingTwo(): Int {
        delay(1000L) //假设在这里做了一些有用的事
        return 11
    }

    private fun test() = runBlocking {
        repeat(8) {
            Log.e(TAG, "协程执行$it 线程id：${Thread.currentThread().id}")
            delay(1000)
        }
    }
}